import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:happy_elf_app/apis/home.dart';
import 'package:happy_elf_app/store/config.dart';
import 'package:happy_elf_app/store/home.dart';
import 'package:happy_elf_app/utils/adaption.dart';
import 'package:happy_elf_app/utils/color.dart';
import 'package:happy_elf_app/utils/globalKey.dart';
import 'package:happy_elf_app/widgets/Toast/index.dart';

class Generate extends StatefulWidget {
  final Function callBack;
  final String targetId;
  const Generate({super.key, required this.callBack, required this.targetId});

  @override
  State<Generate> createState() => _GenerateState();
}

class _GenerateState extends State<Generate>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  final TextEditingController nameController = TextEditingController();
  final TextEditingController wishController = TextEditingController();
  final HomeDataProvider = Provider.of<HomeData>(
    Global.navigatorKey.currentContext!,
    listen: false,
  );

  Map generateData = {};
  bool isGenerating = false;
  int progress = 0; // 生成进度
  late Timer _progressTimer; // 进度计时器

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this);
    _startGenerating(); // 开始生成流程
  }

  @override
  void dispose() {
    _controller.dispose();
    _progressTimer.cancel(); // 确保计时器取消，避免内存泄漏
    nameController.dispose();
    wishController.dispose();
    super.dispose();
  }

  // 开始生成精灵蛋并启动进度计时器
  void _startGenerating() {
    setState(() {
      isGenerating = true;
      generateData = {};
      progress = 0; // 重置进度
    });

    // 启动进度计时器：每2秒增加3%
    _progressTimer = Timer.periodic(const Duration(seconds: 2), (timer) {
      setState(() {
        // 进度最多到99%，等待接口返回后再到100%
        if (progress < 99) {
          progress = (progress + 3).clamp(0, 99); // 确保不超过99
        } else {
          // 达到99%后停止计时器
          timer.cancel();
        }
      });
    });

    // 调用接口创建精灵蛋
    _fetchGenerateGenius();
  }

  // 调用接口创建精灵蛋
  Future<void> _fetchGenerateGenius() async {
    try {
      print('widget.targetId--${widget.targetId}');
      String id = widget.targetId.toString();
      var res = await Home().generateGenius(id);

      // 无论接口成功与否，都停止进度计时
      _progressTimer.cancel();

      if (res['code'] == 200) {
        print('创建精灵蛋成功');
        generateData = res['data'];
        // 接口成功返回，进度直接到100%
        setState(() => progress = 100);
      } else {
        // 接口失败，保持当前进度并提示
        Toast.show(
            context: context, message: '生成失败: ${res['message'] ?? '未知错误'}');
      }
    } catch (e) {
      // 捕获异常（如网络错误）
      _progressTimer.cancel();
      Toast.show(context: context, message: '生成失败，请检查网络');
      print('生成接口异常: $e');
    } finally {
      // 无论结果如何，都标记为生成结束（可选，根据业务需求）
      setState(() => isGenerating = false);
    }
  }

  // 检查是否可以提交
  bool _canSubmit() {
    return !isGenerating && progress >= 100;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 精灵生成容器
        Container(
          width: 350,
          height: 510,
          margin: EdgeInsets.only(top: 16),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(24.px),
            border: Border.all(width: 1.px, color: hexColor('#666666')),
          ),
          child: Column(
            children: [
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(24.px),
                      topRight: Radius.circular(24.px),
                    ),
                  ),
                  child: Column(
                    children: [
                      // 生成进度显示
                      if (isGenerating)
                        Flexible(
                          child: Stack(
                            children: [
                              // 进度条背景
                              Positioned(
                                top: 200,
                                left: 20,
                                child: Container(
                                  padding: const EdgeInsets.only(right: 12),
                                  height: 24,
                                  width: 310,
                                  alignment: Alignment.centerRight,
                                  decoration: BoxDecoration(
                                    border: Border.all(
                                      width: 1.px,
                                      color: hexColor('#cccccc'),
                                    ),
                                    borderRadius: BorderRadius.circular(16),
                                  ),
                                ),
                              ),
                              // 进度条填充
                              Positioned(
                                top: 202,
                                left: 22,
                                child: Container(
                                  height: 20,
                                  width: 310 * (progress / 100), // 按百分比计算宽度
                                  decoration: BoxDecoration(
                                    color: hexColor('#E9614D'),
                                    borderRadius: BorderRadius.circular(20),
                                  ),
                                ),
                              ),
                              // 进度文字
                              Positioned(
                                top: 260,
                                left: 134,
                                child: Text(
                                  '精灵生成${progress}%',
                                  style: const TextStyle(
                                    color: Colors.black,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      // 生成完成后显示精灵图片
                      if (progress >= 100 && generateData['imageUrl'] != null)
                        Expanded(
                          child: Container(
                            alignment: Alignment.center,
                            child: Image.network(
                              generateData['imageUrl'],
                              fit: BoxFit.contain,
                            ),
                          ),
                        ),
                      // 精灵名字输入框
                      Focus(
                        onFocusChange: (hafocus) async {
                          if (!hafocus) {
                            if (generateData['geniusId'] == null) {
                              Toast.show(context: context, message: '请等待精灵生成!');
                              return;
                            }
                            //
                            if (nameController.text != '') {
                              // 接口提交
                              Map data = {
                                "geniusId": generateData['geniusId'],
                                "name": nameController.text,
                                "generateUuid": generateData['generateUuid'],
                                "imageUrl": generateData['imageUrl'],
                              };
                              var res = await Home().setGeniusName(data);
                              if (res['code'] == 200) {
                                Toast.show(
                                    context: context, message: '精灵名字设置成功');
                              }
                            }
                          }
                        },
                        child: Container(
                          width: 200,
                          height: 60.px,
                          margin: const EdgeInsets.only(bottom: 20),
                          child: TextField(
                            controller: nameController,
                            cursorColor: hexColor('#F04136'),
                            cursorWidth: 2.px,
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: Colors.white,
                              contentPadding: const EdgeInsets.only(
                                  bottom: 0, left: 8, top: 10),
                              counterText: "",
                              hintText: '输入精灵名字',
                              hintMaxLines: 1,
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(
                                  color: hexColor('#cccccc'),
                                  width: 1.px,
                                ),
                                borderRadius: BorderRadius.circular(16),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(
                                  color: hexColor('#cccccc'),
                                  width: 1.px,
                                ),
                                borderRadius: BorderRadius.circular(10),
                              ),
                            ),
                            maxLength: 8,
                            maxLines: 1,
                            style: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        // 目标输入框
        Container(
          width: 350,
          height: 60.px,
          margin: EdgeInsets.only(top: 12),
          child: TextField(
            controller: wishController,
            cursorColor: hexColor('#F04136'),
            cursorWidth: 2.px,
            decoration: InputDecoration(
              filled: true,
              fillColor: Colors.white,
              contentPadding:
                  const EdgeInsets.only(bottom: 0, left: 8, top: 10),
              counterText: "",
              hintText: '输入你的目标吧～',
              hintMaxLines: 1,
              focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(
                  color: hexColor('#cccccc'),
                  width: 1.px,
                ),
                borderRadius: BorderRadius.circular(16),
              ),
              enabledBorder: OutlineInputBorder(
                borderSide: BorderSide(
                  color: hexColor('#cccccc'),
                  width: 1.px,
                ),
                borderRadius: BorderRadius.circular(16),
              ),
            ),
            maxLength: 8,
            maxLines: 1,
            style: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w400,
            ),
          ),
        ),
        // 完成按钮
        Container(
          margin: EdgeInsets.only(top: 24),
          width: 100,
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: hexColor(_canSubmit() ? '#e9614d' : '#999999'),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(6),
              ),
              disabledBackgroundColor: hexColor('#999999'), // 禁用状态颜色
            ),
            onPressed: () {
              if (!_canSubmit()) return;
              print('nameController.text${nameController.text}');
              if (nameController.text == '') {
                Toast.show(context: context, message: '请输入精灵名字');
              } else {
                widget.callBack();
              }
            },
            child: const Text(
              ' 完成 ',
              style: TextStyle(fontSize: 18, color: Colors.white),
            ),
          ),
        )
      ],
    );
  }
}
